﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace Yule8xCommon.Applib
{
    public class XMLUtil
    {
        public static string GetAttrValue(XElement xml, string name, string defv = "")
        {
            return (null == xml.Attribute(name)) ? defv : xml.Attribute(name).Value;
        }

        public static string GetNodeValue(XElement xml, string name, string defv = "")
        {
            return (null == xml.Element(name)) ? defv : xml.Element(name).Value;
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml">XML字符串</param>
        /// <returns></returns>
        /// <see cref="http://blog.okbase.net/haobao/archive/62.html"/>
        public static object Deserialize<T>(string xml)
        {
            try
            {
                using (StringReader sr = new StringReader(xml))
                {
                    XmlSerializer xmldes = new XmlSerializer(typeof(T));
                    return xmldes.Deserialize(sr);
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static object Deserialize<T>(Stream stream)
        {
            XmlSerializer xmldes = new XmlSerializer(typeof(T));
            return xmldes.Deserialize(stream);
        }

        /// <summary>
        /// 序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static string Serializer<T>(object obj)
        {
            using (MemoryStream Stream = new MemoryStream())
            {
                XmlSerializer xml = new XmlSerializer(typeof(T));
                try
                {
                    xml.Serialize(Stream, obj); //序列化对象
                }
                catch (InvalidOperationException ex)
                {
                    throw ex;
                }
                Stream.Position = 0;
                using (StreamReader sr = new StreamReader(Stream))
                {
                    string str = sr.ReadToEnd();
                    return str;
                }
            }
        }

        /// <summary>
        /// DataTable转换成XML
        /// <para>必需设置Table.Name</para>
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public static string ConvertDataTableToXML(DataTable dataTable,out string error)
        {
            if (null == dataTable)
            {
                error = "DataTable is null";
                return string.Empty;
            }
            if (string.IsNullOrEmpty(dataTable.TableName))
            {
                dataTable.TableName = "dataTable";
            }
            MemoryStream stream = null;
            XmlTextWriter writer = null;
            try
            {
                error = string.Empty;
                stream = new MemoryStream();
                writer = new XmlTextWriter(stream, Encoding.Default);
                dataTable.WriteXml(writer);
                int count = (int)stream.Length;
                byte[] arr = new byte[count];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(arr, 0, count);
                UTF8Encoding utf = new UTF8Encoding();
                //UnicodeEncoding utf = new UnicodeEncoding();
                return utf.GetString(arr).Trim();
            }
            catch(Exception ex)
            {
                error = ex.Message;
                return string.Empty;
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                    stream.Close();
                    stream.Dispose();
                }
            }
        }
        public static DataSet ConvertXMLToDataSet(string xmlString, out string error)
        {
            StringReader stream = null;
            XmlTextReader reader = null;
            try
            {
                error = string.Empty;
                DataSet xmlDS = new DataSet();
                stream = new StringReader(xmlString);
                reader = new XmlTextReader(stream);
                xmlDS.ReadXml(reader);
                return xmlDS;
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return null;
            }
            finally
            {
                if (reader != null)
                    reader.Close();
                stream.Close();
                stream.Dispose();
            }
        }
    }
}